<!--
    * Time    : 2021-03-13 09:25:28
    * Author  : zhangTj
    * Desc    : 调查问卷
-->

<template>
    <div class="w750">
        <template v-for="(floor, index) in questionList[activeIndex]">
            <component
                v-model="questionList[activeIndex][index]"
                :index="floor.questionIndex"
                :active-index="activeIndex"
                :is="floor.componentName"
                :key="floor.id"
                @pagination="pageChange"
            ></component>
        </template>

        <!-- 提交按钮 -->
        <div class="px-3 d-flex text-center" v-if="activeIndex == questionList.length - 1">
            <div
                v-if="activeIndex"
                @click="pageChange(-1)"
                class="iconfont iconArrowLeft rounded-4 bg-main text-fff mr-1"
                style="width: 68px; height: 44px; line-height: 44px"
            ></div>
            <van-button id="submit" @click="submitForm" type="primary" :color="themes.color" block>提交</van-button>
        </div>

        <Noempty v-if="error && !partLoading" :pic="require('@/assets/images/personal-no-good.png')" :title="errorText" />
        <part-loading v-model="partLoading" backgroundColor="#fff" height="400px" size="24px" :color="themes.color" />
    </div>
</template>

<script>
import Noempty from '@/components/Noempty/Noempty'
import PartLoading from '@/components/PartLoading/PartLoading'
import { questionnaireApi } from '@/api/questionnaire'
import { mapState } from 'vuex'
import checkInfo from '@/utils/checkInfo'
import { tokenManage } from 'utils/Cache'

// 楼层数据
import TextInput from './components/floor/TextInput'
import Pagination from './components/floor/Pagination'
import PhotoSelect from './components/floor/PhotoSelect'
import Picture from './components/floor/Picture'
import Region from './components/floor/Region'
import RichText from './components/floor/RichText'
import TextAreaInput from './components/floor/TextAreaInput'
import TextSelect from './components/floor/TextSelect'
import DateInput from './components/floor/DateInput'

export default {
    name: 'questionnaire',
    components: {
        PartLoading,
        Noempty,
        TextInput,
        Pagination,
        PhotoSelect,
        Picture,
        Region,
        RichText,
        TextAreaInput,
        TextSelect,
        DateInput
    },
    data() {
        return {
            id: '', // id
            partLoading: true,
            error: false, // 错误时显示占位图
            errorText: '暂无该调查问卷数据',
            activeIndex: 0, // 当前循环的数组下标
            rawData: {}, // 原始数据
            questionList: [] // 楼层数据(二维数组)
        }
    },
    computed: {
        ...mapState(['themes'])
    },
    watch: {},
    created() {},
    destroyed() {},
    mounted() {
        if (this.$route.query.id) {
            this.id = this.$route.query.id
        }
        this.getResult()
    },
    methods: {
        // 获取问卷详情
        getDetail() {
            questionnaireApi
                .questionnaireId(this.id)
                .then((res) => {
                    if (!res.success) {
                        return void this.$toast(res.msg)
                    }

                    document.title = res.result.title

                    this.rawData = res.result

                    // 以分页组件作为切割，变成一个二维数组
                    const questionData = JSON.parse(res.result.content)
                    let showList = []
                    let questionIndex = 0
                    questionData.forEach((item, index) => {
                        if (!['pagination', 'richText'].includes(item.type)) {
                            item.questionIndex = questionIndex
                            questionIndex++
                        }
                        showList.push(item)
                        if (item.type == 'pagination') {
                            this.questionList.push(showList)
                            showList = []
                        }
                        if (index == questionData.length - 1) {
                            this.questionList.push(showList)
                        }
                    })
                })
                .catch((err) => {
                    this.error = true
                })
                .finally((_) => {
                    this.partLoading = false
                })
        },

        // 获取问卷是否填写过
        getResult() {
            return questionnaireApi
                .questionnaireHaveFilledIn({
                    id: this.id
                })
                .then((res) => {
                    if (!res.success) {
                        this.error = true
                        return void this.$toast(res.msg)
                    }

                    if (res.result.code == 0) {
                        if (!tokenManage.isLogin()) {
                            // this.$router.replace({ path: '/login', query: { redirect: this.$route.fullPath } })
							this.$utils.goLoginPage(this)
                            return
                        }
                    }
                    if (res.result.code == 10) {
                        this.$router.replace({
                            path: '/questionnaireResult',
                            query: { id: res.result.id, questionnaireId: this.id, resultShowFlag: Number(res.result.resultShowFlag) }
                        })
                        return
                    }
                    if (res.result.code == 20) {
                        this.error = true
                        this.errorText = '该问卷已过期'
                        this.partLoading = false
                        return
                    }
                    if (res.result.code == 15) {
                        this.error = true
                        this.errorText = '该问卷暂未开始'
                        this.partLoading = false
                        return
                    }
                    if (res.result.code == 30) {
                        this.error = true
                        this.errorText = '该问卷不存在'
                        this.partLoading = false
                        return
                    }

                    this.getDetail()
                })
                .catch((err) => {
                })
        },

        // 提交表单
        submitForm() {
			this.$utils.uDebounce(() => {
				questionnaireApi
				    .questionnaire({
				        questionnaireId: this.id,
				        resultContent: JSON.stringify(this.questionList.flat())
				    })
				    .then((res) => {
				        if (!res.success) return void this.$toast(res.msg)
				
				        this.$toast('提交成功')
				
				        this.$router.replace({
				            path: '/questionnaireResult',
				            query: { id: res.result, questionnaireId: this.id, resultShowFlag: Number(this.rawData.resultShowFlag) }
				        })
				    })
				    .catch((err) => {
				    })
			})
        },

        // 页数改变
        pageChange(num) {
            // 上一页可以直接返回上一页
            if (num === -1) {
                this.activeIndex += num
                return
            }

            // 进行校验
            for (let item of this.questionList[this.activeIndex]) {
                if (item.required && !checkInfo([{ type: 'hasValue', value: item.content }])) {
                    return void this.$toast(`请完成题目${item.questionIndex + 1}`)
                }
                if ((item.required || item.content) && item.type == 'phone' && !checkInfo([{ type: 'phone', value: item.content }])) {
                    return void this.$toast(`题目${item.questionIndex + 1}-请输入正确的手机号码`)
                }
                if ((item.required || item.content) && item.type == 'email' && !checkInfo([{ type: 'email', value: item.content }])) {
                    return void this.$toast(`题目${item.questionIndex + 1}-请输入正确的邮箱`)
                }
            }

            this.activeIndex += num
        }
    }
}
</script>
